package com.dmjj.util.aspect;

import com.alibaba.fastjson.JSON;
import com.dmjj.log.pojo.SysLog;
import com.dmjj.log.service.LoggerService;
import com.dmjj.util.annoation.SysLogger;
import com.dmjj.util.util.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.TimeoutException;

@Aspect
@Component
public class SysLoggerAspect {
    @Autowired
    private LoggerService loggerService;
 
    @Pointcut("@annotation(com.dmjj.util.annoation.SysLogger)")
    public void loggerPointCut() {
 
    }
 
    @Before("loggerPointCut()")
    public void saveSysLog(JoinPoint joinPoint) throws IOException, TimeoutException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
 
        SysLog sysLog = new SysLog();
        SysLogger sysLogger = method.getAnnotation(SysLogger.class);
        String MenuIds = request.getParameter("MenuIds")!=null?request.getParameter("MenuIds"):null;
        sysLog.setMenuIds(MenuIds);
        if(sysLogger != null){
            //注解上的描述
            sysLog.setOperation(sysLogger.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params="";
        for(Object o:args){
            params+= JSON.toJSONString(o);
        }
        if(!StringUtils.isEmpty(params)) {
            sysLog.setParams(params);
        }
        //设置IP地址
        sysLog.setIp(HttpUtils.getIpAddress());
        //用户名
//        String username = UserUtils.getCurrentPrinciple();
//        if(!StringUtils.isEmpty(username)) {
//            sysLog.setUsername(username);
//        }
        sysLog.setCreateDate(new Date());
        //保存系统日志
        loggerService.log(sysLog);
    }
 
}
